package com.carmanagement

class User {

    transient springSecurityService

    String username
    String password
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    static hasMany = [vehicles : Vehicle]

    static transients = ['springSecurityService']

    static constraints = {
	username blank: false, unique: true
	password blank: false
    }

    static mapping = { password column: '`password`' }

    Set<Role> getAuthorities() {
	UserRole.findAllByUser(this).collect { it.role } as Set
    }

    def isAdmin(){
	def role = getAuthorities().find { it.authority.equals(RoleEnum.ADMIN_ROLE.value) }

	return role != null
    }

    def beforeInsert() {
	encodePassword()
    }

    def beforeUpdate() {
	if (isDirty('password')) {
	    encodePassword()
	}
    }

    def beforeDelete() {
        UserRole.removeAll this
    }

    protected void encodePassword() {
	password = springSecurityService.encodePassword(password)
    }
}
